<template>
  <div>
    <search-bar @onSearch="onSearch" />
    <div class="btns">
      <el-button type="primary" @click="$router.push('/itemAdd')">增加</el-button>
      <el-upload action="#" accept=".xlsx, .xls" :before-upload="uploadExceltoData">
        <el-button>批量导入</el-button>
      </el-upload>
      <a href="javascript:;" @click="exportFile">下载excel模板</a>
    </div>
    <el-table :data="items" style="width: 100%" height="600px">
      <el-table-column prop="itemName" label="商品名" />
      <el-table-column prop="price" label="价格">
        <template #default="{ row }">
          <el-tag type="success">{{ row.price }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="desc" label="描述">
        <template #default="{ row }">
          <el-tooltip class="box-item" effect="dark" placement="bottom">
            <div>
              {{ row.desc.length > 15 ? row.desc.substring(0, 15) + "..." : row.desc }}
            </div>
            <template #content>
              <div style="width: 500px; background: #fcd3c3">
                {{ row.desc }}
              </div>
            </template>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="sale" label="销量">
        <template #default="{ row }">
          <el-tag :color="row.sale > 500 ? 'red' : 'green'" type="success">{{
            row.sale
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="onsale" label="是否上架">
        <template #default="{ row }">
          <el-switch
            v-model="row.onsale"
            inline-prompt
            active-text="上架"
            inactive-text="下架"
            @change="switchItemOnsale(row.id, row.onsale)"
            :style="{
              '--el-switch-on-color': '#13ce66',
              '--el-switch-off-color': '#ff4949',
            }"
          />
        </template>
      </el-table-column>
      <el-table-column prop="thumb" label="封面图片">
        <template #default="{ row }">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.thumb"
            :zoom-rate="1.2"
            :preview-src-list="row.pics"
            :initial-index="0"
            fit="cover"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="createAt" label="上架时间" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="delItem(row.id)">删除</el-button>
          <el-button @click="enterUpdateItem(row.id)" type="primary" size="small"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      layout="prev, pager, sizes, next, jumper"
      v-model:page-size="pageSize"
      v-model:current-page="page"
      :total="total"
    />
    <!-- 分页组件 -->
  </div>
</template>

<script>
import { fetchItems, updateItem, delItem, addItems } from "@a/item";
import SearchBar from "@/components/SearchBar.vue";
import { utils, writeFileXLSX, read } from "xlsx";
export default {
  name: "ItemLists",
  data() {
    return {
      items: [],
      total: 0,
      searchParams: {},
      page: 1,
      pageSize: 10,
    };
  },
  watch: {
    page() {
      this.fetchItems();
    },
    pageSize() {
      this.fetchItems();
    },
  },
  methods: {
    delItem(id) {
      this.$confirm("此操作会彻底删除该商品,继续吗?", "删除商品").then(() => {
        delItem(id).then((res) => {
          if (res.data.code === 200) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                this.fetchItems();
              },
            });
          }
        });
      });
    },
    switchItemOnsale(id, onsale) {
      // 行内修改商品上下架状态
      updateItem({
        id,
        onsale,
      }).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            type: "success",
            message: res.data.msg,
            duration: 1500,
            onClose: () => {
              this.fetchItems();
            },
          });
        }
      });
    },
    enterUpdateItem(id) {
      this.$router.push({
        path: "/itemUpdate",
        query: {
          id,
        },
      });
    },
    uploadExceltoData(file) {
      // 将本地excel解析成数组，并批量上传商品
      const fd = new FileReader();
      fd.readAsArrayBuffer(file);
      fd.onload = () => {
        const wb = read(fd.result);
        const data = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        const _data = data.map((el) => {
          return {
            itemName: el.商品名,
            price: el.商品价格,
            desc: el.商品描述,
          };
        });
        console.log(_data);
        // 发送请求给批量新增商品接口
        addItems({
          items: _data,
        }).then((res) => {
          if (res.data.code === 200) {
            this.$message({
              type: "success",
              message: res.data.msg,
              duration: 1500,
              onClose: () => {
                this.fetchItems();
              },
            });
          }
        });
      };
      return false;
    },
    exportFile() {
      // 导出excel模板
      // 导出数据
      const data = [
        {
          商品名: "商品n",
          商品价格: 10,
          商品描述: "这是描述",
        },
      ];
      const ws = utils.json_to_sheet(data);
      const wb = utils.book_new();
      utils.book_append_sheet(wb, ws, "Data");
      writeFileXLSX(wb, "商品表.xlsx");
    },
    onSearch(searchParams) {
      this.searchParams = searchParams;
      this.fetchItems();
    },
    fetchItems() {
      fetchItems({
        ...this.searchParams,
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        if (res.data.code === 200) {
          this.items = res.data.data.lists;
          this.total = res.data.data.total;
        }
      });
    },
  },
  created() {
    this.fetchItems();
  },
  components: {
    SearchBar,
  },
};
</script>

<style lang="scss" scoped>
.btns {
  display: flex;
  align-items: center;
}
</style>
